package com.taylor.community.service;

import com.taylor.community.util.RedisKeyUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.connection.RedisStringCommands;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author 26925
 */
@Service
public class DataService {
    @Autowired
    private RedisTemplate redisTemplate;
    private SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");

    /**
     * 将指定的ip计入UV
     * @param ip
     */
    public void recordUv(String ip){
        String redisKey = RedisKeyUtil.getUvKey(df.format(new Date()));
        redisTemplate.opsForHyperLogLog().add(redisKey,ip);
    }

    /**
     * 统计指定范围内的UV
     * @param start
     * @param end
     * @return
     */
    public long calculateUv(Date start,Date end){
        if(start == null || end ==null){
            throw new IllegalArgumentException("参数不能为空!");
        }
        if (start.after(end)) {
            throw new IllegalArgumentException("开始日期不能大于结束日期");
        }
        //先收集指定范围的key
        List<String> keyList = new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        //设定当前时间
        calendar.setTime(start);
        //当前时间已经超过结束日期就结束循环
        while (!calendar.getTime().after(end)){
            String key = RedisKeyUtil.getUvKey(df.format(calendar.getTime()));
            keyList.add(key);
            //calendar.DATE指定单位为天，当前时间往后推1天
            calendar.add(Calendar.DATE,1);
        }
        //合并当前范围的数据
        String redisKey = RedisKeyUtil.getUvKey(df.format(start),df.format(end));
        //list底层是动态数组 union方法的参数前者是key，后者就是要合并的目标值
        Long size = redisTemplate.opsForHyperLogLog().union(redisKey,keyList.toArray());
        return size;
    }

    /**
     * 将指定的用户存入DAU
     * @param userId
     */
    public void recordDau(int userId){
        String redisKey = RedisKeyUtil.getDauKey(df.format(new Date()));
        redisTemplate.opsForValue().setBit(redisKey,userId,true);
    }

    /**
     * 统计某范围内的活跃用户
     * 会进行or运算 假设统计7天内的活跃用户 则这7天内任何一天访问过 进行or运算后就是true 就是活跃用户
     * @param start
     * @param end
     * @return
     */
    public long calculateDau(Date start,Date end){
        if(start == null || end == null){
            throw new IllegalArgumentException("参数不能为空!");
        }
        if (start.after(end)) {
            throw new IllegalArgumentException("开始日期不能大于结束日期");
        }
        //获取该日期范围内的key
        List<byte[]> keyList= new ArrayList<>();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(start);
        while (!calendar.getTime().after(end)){
            String key = RedisKeyUtil.getDauKey(df.format(calendar.getTime()));
            //string转为byte数组
            keyList.add(key.getBytes());
            calendar.add(Calendar.DATE,1);
        }
        //进行or运算，原因是这段时间内该用户登录过，or运算得到true，也就是算活跃用户
        //RedisTemplate没有提供对bitmap的操作接口，所以通过RedisCallback接口来执行原始的redis命令
        return (long) redisTemplate.execute(new RedisCallback() {
            @Override
            public Object doInRedis(RedisConnection redisConnection) throws DataAccessException {
                String key = RedisKeyUtil.getDauKey(df.format(start),df.format(end));
                redisConnection.bitOp(RedisStringCommands.BitOperation.OR,
                        key.getBytes(),keyList.toArray(new byte[0][0]));

                return redisConnection.bitCount(key.getBytes());
            }
        });
    }

}

